﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using Twipler.App.DataDoc;
using Twipler.App.Machine;

namespace Twipler.App.Render.Tree
{
    public class ActionItem : AbstractItem
    {
        private string _name;
        private string _intoVariable;
        private StaticMethodCall _staticCall;
        private string _sucessMessage;

        public override List<AbstractItem> Children { get { return null; } }

        public static ActionItem Create(string name, StaticMethodCall staticCall, string intoVariable, string sucessMessage)
        {
            return new ActionItem()
                       {
                           _name = name,
                           _staticCall = staticCall,
                           _intoVariable = intoVariable,
                           _sucessMessage = sucessMessage
                       };
        }

        public override string PostbackId
        {
            get
            {
                return GetHashCode().ToString();
            }
        }

        public override void Render(System.Text.StringBuilder html, App.Machine.Environment environment)
        {
            if (!environment.Variables_Contains(_name))
                environment.Variables_Add(_name, PostbackId);
        }

        public override void Postback(Machine.Environment environment)
        {
            IDataDoc returned = _staticCall.Invoke(environment) as IDataDoc;

            if (returned == null)
                return;

            if (!string.IsNullOrEmpty(_intoVariable))
            {
                environment.Variables_Add(_intoVariable, returned);

                if (!string.IsNullOrEmpty(_sucessMessage))
                    returned.IsSucessSetMessage(_sucessMessage);
            }
        }

    }

}